

//
//  CPJMainViewController.swift
//  Sina
//
//  Created by YYY on 2017/7/24.
//  Copyright © 2017年 成品家（北京）网路科技有限公司. All rights reserved.
//


/*
使用代理传递消息是为了在控制器和视图之间解耦，让视图能够被多个控制器复用
 
 */
import UIKit

import SVProgressHUD

class CPJMainViewController: UITabBarController {

    //定时器
    var myTimer: Timer?
    
    //懒加载(完整)
    fileprivate lazy var middleAddButton: UIButton = { () -> UIButton in
        //self.view.center
        let tabBarAddButton = UIButton()
        
        tabBarAddButton.setImage(UIImage(named: "tabbar_compose_icon_add"), for: .normal)
        tabBarAddButton.setBackgroundImage(UIImage(named: "tabbar_compose_button"), for: .normal)
        return tabBarAddButton
        }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //注册监听者
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin), name: NSNotification.Name(rawValue: UserShouldLoginNotification), object: nil)
        
        setUpChildViewController()
        addButton()
        
        setUpTimer()
        
        ///设置新特性
        setupNewFeatures()
        
        //设置代理
        delegate = self
        // Do any additional setup after loading the view.
    }

    @objc private func userLogin(notify: Notification)
    {
        
        var when = DispatchTime.now()
        
        
        if notify.object != nil
        {
            SVProgressHUD.setDefaultMaskType(.gradient)
            SVProgressHUD.showInfo(withStatus: "登录超时，请重新登录")
            
            when = DispatchTime.now() + 1
        }
        
       
        //延迟1s后执行 DispatchQueue.main.asyncAfter
        DispatchQueue.main.asyncAfter(deadline: when) {
            
            SVProgressHUD.setDefaultMaskType(.clear)
            
            let vc = CPJLoginViewController()
            
            let navVC = UINavigationController(rootViewController: vc)
            
            self.present(navVC, animated: true, completion: nil)
        }
    }

    
    //销毁时钟 
    deinit
    {
        myTimer?.invalidate()
        //移除通知
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: UserShouldLoginNotification), object: nil)
    }
    //private 能够保证方法私有，仅在当前对象被访问
    //@objc 允许这个函数在运行时，通过OC的消息机制被调用
    @objc func tabBarAddAction()
    {
//        if !CPJNetworkManager.shared.userLogin
//        {
//            SVProgressHUD.show(withStatus: "用户未登录")
//            return
//        }
        //添加方法
        let view = CPJComposeView.composeView()

        view.show { [weak view] (clsName) in
            
            guard let clsName = clsName,
                let cls = NSClassFromString(Bundle.main.nameSpace + "." + clsName) as? UIViewController.Type else
            {
                view?.removeFromSuperview()
                return
            }
            
            let vc = cls.init()
            let navVC = UINavigationController(rootViewController: vc)
            
            //navVC.view.layoutIfNeeded()
            
            self.present(navVC, animated: true)
            {
                view?.removeFromSuperview()
            }
        }
    }
    
    //设置设备方向
    //portrait  竖屏  肖像
    //landscape 横屏  风景画
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask
    {
        return .portrait
    }
}

extension CPJMainViewController
{
    ///设置新特性
    fileprivate func setupNewFeatures()
    {
        if !CPJNetworkManager.shared.userLogin
        {
            return
        }
        let newView = version ? CPJNewFeatureView.newFeatureView() : CPJWelcomeView.welcomeView()
        //newView.frame = view.bounds
        view.addSubview(newView)
    }
    
    //extension中可以定义计算型数据，不占用空间
    //构造函数为变量分配空间
    private var version: Bool
    {
        let currentVersion = Bundle.main.shortVersion
        
        let path = (kDocumentPath as NSString).appendingPathComponent("version")
        
        let sandBoxVersion = (try? String(contentsOfFile: path)) ?? ""
        try? currentVersion.write(toFile: path, atomically: true, encoding: .utf8)
        
        
        return currentVersion != sandBoxVersion
    }
}

extension CPJMainViewController: UITabBarControllerDelegate
{
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        print("切换到：\(viewController)")
        
        //let index = childViewControllers.index(of: viewController)
        
        let index = viewControllers?.index(of: viewController)
        
        if selectedIndex==0 && index==selectedIndex
        {
            
            let navVC = childViewControllers[0] as! UINavigationController
            let vc = navVC.childViewControllers[0] as! CPJHomePageViewController
            
            vc.tableView?.setContentOffset(CGPoint(x: 0, y: -64), animated: true)
            
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1, execute: { 
                vc.loadData()
            })
            
            tabBar.items?[0].badgeValue = nil
            UIApplication.shared.applicationIconBadgeNumber = 0
            
            
        }
        return !viewController.isMember(of: UIViewController.self)
    }
}
extension CPJMainViewController
{
    //初始化定时器
    fileprivate func setUpTimer()
    {
        myTimer = Timer.scheduledTimer(timeInterval: 50, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
    }
    
    
    /// 时钟触发方法
    @objc private func updateTimer()
    {
        if !CPJNetworkManager.shared.userLogin
        {
            return
        }
        CPJNetworkManager.shared.loadUnReadData { (count) in
            print("未读的\(count)条微博数据")
            //设置首页分栏的badgeValue
            self.tabBar.items?[0].badgeValue = (count>0) ? "\(count)" : nil
            //设置应用的badgeValue
            UIApplication.shared.applicationIconBadgeNumber = count
        }
    }
}
extension CPJMainViewController
{
    //extension 类似OC中的分类，在Swift中可以用来切分代码块
    //可以把相近功能的函数，放在一个extension中
    //便于代码维护
    //和OC中的分类一样，extension中不能定义属性
    // MARK - 设置界面
    fileprivate func setUpChildViewController()
    {
        //获取沙盒json路径
        //let docPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let newPath = (kDocumentPath as NSString) .appendingPathComponent("main.json")
        
        var data = NSData(contentsOfFile: newPath)
        if data == nil
        {
            //沙盒中不存在，从bundle中取
            let path = Bundle.main.path(forResource: "main", ofType: "json")
            data = NSData(contentsOfFile: path!)
        }
        //反序列化，抛出异常
        //方法1 try? 推荐使用 如果解析成功，就有值，否则为nil
        //方法2 try! 强烈不推荐 如果解析成功，就有值，否则崩溃，有风险
        //方法3 do catch try 语法结构复杂 能够接受错误，并且输出错误
        
        //OC语言，ARC开发，编译器自动添加retain、release、autorelease,如果try catch使用不平衡，就会出现内存泄露
   
        
        guard let controllers = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String: AnyObject]]  else
        {
            return
        }
        
        var vcArray = [UIViewController]()
        
        for dict in controllers!
        {
            vcArray.append(controllerDict(dict: dict))
        }
        viewControllers = vcArray
    }
    
    fileprivate func controllerDict(dict: [String: AnyObject]) -> UIViewController
    {
        //dict： 类名、图片、文字
        //取得字典内容
        guard let className = dict["className"] as? String,
            let title = dict["title"] as? String,
            let imageName = dict["imageName"] as? String,
            let vc = NSClassFromString(Bundle.main.nameSpace + "." + className) as? CPJBaseViewController.Type,
            let visitorDict = dict["visitorDict"] as? [String: String] else
        {
            return UIViewController()
        }
        //实例化视图控制器
        let viewController = vc.init()
        
        viewController.visitorInfoDictionary = visitorDict
        //设置标题
        viewController.title = title
        //设置分栏图片
        viewController.tabBarItem.image = UIImage(named: imageName)
        viewController.tabBarItem.selectedImage = UIImage(named: imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        //分栏字体默认是12
        
        viewController.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.black],for: .normal)
        //[NSFontAttributeName: UIFont.systemFont(ofSize: 13)]
        
        let navVC = CPJNavigationViewController(rootViewController: viewController)
        return navVC
    }
    
    // MARK - 中间添加按钮
    fileprivate func addButton()
    {
        tabBar.addSubview(middleAddButton)
        
        let count = CGFloat(childViewControllers.count)
        
        let width = tabBar.bounds.width/count 
        //insetBy相当于CGRectInset 负数表示向外缩进，正数表示向内缩进
        middleAddButton.frame = tabBar.bounds.insetBy(dx: 2*width, dy: 0)
        middleAddButton.addTarget(self, action: #selector(tabBarAddAction), for: .touchUpInside )
    }
}
